package com.zoe.onelink.business.util.ws;


import com.zoe.onelink.common.enumeration.ExceptionCodeEnum;
import com.zoe.onelink.common.exception.ApiException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;

/**
 * <p>标题: HTTPS请求</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2018</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: cxy
 * @date: 2018/6/14
 */
@Deprecated
public class HttpsRequestUtil {

    /**
     * 请求获取数据的超时时间(即响应时间)，单位毫秒
     */
    private static final int READ_TIME_OUT = 30000;

    /**
     * POST请求
     *
     * @param requestUrl 请求地址
     * @param paramsStr  请求参数
     * @return
     */
    public static String post(String requestUrl, String paramsStr) throws Exception {
        return doRequest(requestUrl, "POST", paramsStr, READ_TIME_OUT);
    }

    /**
     * POST请求
     *
     * @param requestUrl  请求地址
     * @param paramsStr   请求参数
     * @param readTimeOut 超时时间 单位毫秒
     * @return
     */
    public static String post(String requestUrl, String paramsStr, int readTimeOut) throws Exception {
        return doRequest(requestUrl, "POST", paramsStr, readTimeOut);
    }

    /**
     * GET请求
     *
     * @param requestUrl 请求地址
     * @param paramsStr  请求参数
     * @return
     */
    public static String get(String requestUrl, String paramsStr) throws Exception {
        return doRequest(requestUrl, "GET", paramsStr, READ_TIME_OUT);
    }

    /**
     * GET请求
     *
     * @param requestUrl  请求地址
     * @param paramsStr   请求参数
     * @param readTimeOut 超时时间 单位毫秒
     * @return
     */
    public static String get(String requestUrl, String paramsStr, int readTimeOut) throws Exception {
        return doRequest(requestUrl, "GET", paramsStr, readTimeOut);
    }

    /**
     * 处理https GET/POST请求
     * 请求地址、请求方法、参数
     */
    public static String doRequest(String requestUrl, String requestMethod, String paramsStr, int readTimeOut) throws Exception {
        String result = null;
        try {
            //创建SSLContext
            SSLContext sslContext = SSLContext.getInstance("SSL");
            TrustManager[] tm = {new MyX509TrustManager()};
            //初始化
            sslContext.init(null, tm, new java.security.SecureRandom());
            //获取SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setReadTimeout(readTimeOut);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(requestMethod);
            //设置当前实例使用的SSLSoctetFactory
            conn.setSSLSocketFactory(ssf);
            conn.connect();
            //往服务器端写内容
            if (null != paramsStr) {
                OutputStream os = conn.getOutputStream();
                os.write(paramsStr.getBytes("utf-8"));
                os.close();
            }

            //读取服务器端返回的内容
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            StringBuffer buffer = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }

            result = buffer.toString();
        } catch (Exception e) {
            ByteArrayOutputStream buf = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(buf, true));
            String expMessage = buf.toString();
            buf.close();

            throw ApiException.createEx(ExceptionCodeEnum.HTTPS_ERROR, expMessage, requestUrl, paramsStr, e.getMessage());
        }
        return result;
    }
}
